package com.xc.disk.service.impl;

import com.sun.mail.util.MailSSLSocketFactory;
import com.xc.disk.bean.MailHtmlBean;
import com.xc.disk.config.Constants;
import com.xc.disk.service.MailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.util.Properties;

/**
 * <p>项目名称: Stars</p>
 * <p>描述: 邮件服务实现类</p>
 * <P>创建人:小程 </p>
 * <P>创建人邮箱: 779943476@qq.com</p>
 * <p>创建时间: 2019/10/30</p>
 *
 * @version v1.0
 */
@Service
public class MailServiceImpl implements MailService {

    @Autowired
    private Constants constants;

    @Override
    public void sendHtmlMail(MailHtmlBean mailHtmlBean) {
        //是否使用ssl加密,qq需要使用
        Properties properties = System.getProperties();
        try {
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            properties.put("mail.smtp.ssl.enable", true);
            properties.put("mail.smtp.ssl.socketFactory", sf);

            //是否启用验证,true:启用,false:不启用,默认启用
            properties.put("mail.smtp.auth", true);
            //邮件服务器地址
            properties.setProperty("mail.smtp.host", "smtp.qq.com");

            //添加验证
            Session session = Session.getDefaultInstance(properties, new Authenticator() {
                public PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(constants.getMailAccount(), constants.getAuthorizationCode()); //发件人邮件用户名、密码
                }
            });

            //创建消息
            MimeMessage message = new MimeMessage(session);
            //发件人地址
            message.setFrom(new InternetAddress(constants.getMailAccount(), constants.getSystemName()));
            //收件人地址
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(mailHtmlBean.getAddressee()));
            //标题Title
            message.setSubject(mailHtmlBean.getTitle());
            //html文本
            message.setContent(mailHtmlBean.getHtml(), "text/html;charset=utf-8");
            // 发送消息
            Transport.send(message);
        } catch (GeneralSecurityException | MessagingException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    }
}
